<?php

/**
 * Class User_info_service 用户资料相关业务逻辑
 * @author: Calvin
 * @email : hongbinfu@163.com
 * @readme: 用户注册业务逻辑处理类
 */
class User_info_service extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->config->load("user");
        $this->lang->load("user");
        $this->load->library("curl");
    }

    /**
     * 获取用户信息
     * @param $uid 用户的id
     * @param string $fields 所需字段
     * @return mixed
     */
    public function get_user_info($uid,$fields="*")
    {
        return $this->user_model->get_user_info(array("id"=>$uid),$fields);
    }

    public function update_user_info($uid,$data)
    {
        if(empty($uid) || empty($data))
        {
            return $this->set_error(1003);
        }
        $save = $this->user_model->update_user_info(array("id"=>$uid),$data);
        if($save===FALSE)
        {
            return $this->set_error(1002);
        }
        else
        {
            return TRUE;
        }
    }

    public function update_user_info_by_phone($phone,$data)
    {
        if(empty($phone) || empty($data))
        {
            return $this->set_error(1003);
        }
        $save =  $this->user_model->update_user_info(array("mobile"=>$phone),$data);
        if($save===FALSE)
        {
            return $this->set_error(1002);
        }
        else
        {
            return TRUE;
        }
    }
    public function update_user_info_by_email($email,$data)
    {
        if(empty($email) || empty($data))
        {
            return $this->set_error(1003);
        }
        $save =  $this->user_model->update_user_info(array("email"=>$email),$data);
        if($save===FALSE)
        {
            return $this->set_error(1002);
        }
        else
        {
            return TRUE;
        }
    }

    /**
     * 获取用户已用空间
     * @param $uid
     * @param int $type 0获取所有 1：总空间 2:已用空间
     * @return int
     */
    public function get_space($uid,$type=0)
    {
        if(empty($uid))
        {
            return $this->set_error(1003);
        }
        $row = $this->user_model->get_user_info(array("id"=>$uid),"capacity,used_space");
        if(!empty($row))
        {
            switch($type)
            {
                case 1 :
                    return $row['capacity'];
                    break;
                case 2 :
                    return $row['used_space'];
                    break;
                default :
                    return array("capacity"=>$row['capacity'],"used_space"=>$row['used_space']);
                    break;
            }
        }
        else
        {
            //用户ID不存在
            return $this->set_error(5008);
        }
    }

    //用户空间是否够用
    public function space_enough($uid)
    {
        $info = $this->get_space($uid);
        if($info['capacity']<=$info['used_space'])
        {
            return $this->set_error(5014);
        }
        else
        {
            return TRUE;
        }
    }

    /**
     * 获取格式化后的空间信息
     * @param $uid
     * @return mixed
     */
    public function get_format_space($uid)
    {
        if(empty($uid))
        {
            return $this->set_error(1003);
        }

        $space = $this->get_space($uid);
        return $this->get_format_space_info($space);
    }

    /**
     * 空间数据格式化
     * @param $space 空间的数据
     * @return bool
     */
    public function get_format_space_info($space) {
        if (empty($space) || !is_array($space)) return $this->set_error(1003);

        $ret ['percent'] = sprintf("%f",$space['used_space']/$space ['capacity']);
        $ret ['used_space'] = $this->format_space($space['used_space']);
        $ret ['capacity'] = $this->format_space($space['capacity']);
        return $ret;
    }

    /**
     * 格式化空间单位
     * @param $byte
     * @return float|int|string
     */
    public function format_space($byte)
    {
        //小于1K
        if($byte<1024)
        {
            $b = $byte;
            $unit = "B";
        }
        //小于1MB
        else if ($byte < 1048576)
        {
            $b = round(sprintf("%f",$byte / 1024),2);
            $unit = "KB";
        }
        else if ($byte < 1073741824)
        {
            $b = round(sprintf("%f",$byte / 1048576),2);
            $unit = "MB";
        }
        else if($byte < 1099511627776)
        {
            $b = round(sprintf("%f",$byte/1073741824),2);
            $unit = "GB";
        }
        else
        {
            $b = round(sprintf("%f",$byte/1099511627776),2);
            $unit = "TB";
        }
        $b .= $unit;
        return $b;
    }

    /**
     *
     * 上传用户头像
     * @param $uid 用户id
     * @param string $old_face 旧头像（如果不传该参数旧头像文件会在新头像上传成功后被清除）
     * @param string $post_key
     * @return array
     */
    public function upload_face($uid,$old_face="",$post_key="upload_file")
    {
        $default_path = $this->config->item("default_upload_path");
        $default_url = $this->config->item("default_upload_url");
        $max_size = $this->config->item("default_upload_img_max_size");
        $uuid = md5($uid);
        $dir = $default_path."user/".$uuid."/face/";
        $url = $default_url."user/".$uuid.'/face/';
        Common::create_folder($dir);
        $config['upload_path'] = $dir;
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size'] = $max_size;
        $config['file_name']  = time();
        $this->load->library('upload', $config);
        //$post_key = 'upload_file';
        $return_data = array();
        //删除头像临时文件
        if(! $this->upload->do_upload($post_key)) {
            return $this->set_error(1010,NULL,NULL,$this->upload->display_errors('',''));
           // return Common::ajax_return(1010,$this->upload->display_errors('',''));
        } else {
            //$file_data = array('upload_data' => $this->upload->data(), 'error' => 0);
            $file_data = $this->upload->data();
            $config['image_library'] = 'gd2';
            $config['source_image'] = $dir.$file_data['file_name'];
            $config['create_thumb'] = FALSE;
            $config['maintain_ratio'] = TRUE;
            $config['width'] = config_item("face_w");
            $config['height'] = config_item("face_h");
            $this->load->library('image_lib', $config);
            if(!$this->image_lib->resize()){
                return $this->set_error(5018);
            }
            $return_data['img'] = $url.$file_data['file_name'];
            $exclude = array($return_data['img']);
            if(!empty($old_face))
            {
                $exclude[] = $old_face;
            }
            $this->clear_face_tmp($dir,$exclude);
           /* if($change_now)
            {
                //$this->update_user_info($uid,array("image"=>$return_data['img']));
                $return_data['img'].= "?t=".time();
            }*/
            /*$data = array(
                    'image' => $url.$file_data['upload_data']['file_name']
                    );*/
            /*$old_image = $this->login_service->get_user_info("image");
            if($old_image){
                $path = $old_image;
                if(file_exists($path)){
                    unlink($path);//删除旧的头像
                }
            }*/
            //$this->user_model->update($this->uid, $data);
            //echo json_encode($return_data);
            return $return_data;
        }
    }

    public function clear_face_tmp($dir,$exclude="")
    {

        if(!is_dir($dir))
        {
            return TRUE;
        }
        $dir= realpath($dir);
        $exclude_arr = array();
        if(!is_array($exclude))
        {
            $exclude_arr[]= realpath($this->input->server("DOCUMENT_ROOT").$exclude);
        }
        else
        {
            foreach($exclude as $ex)
            {
                $exclude_arr[]= realpath($this->input->server("DOCUMENT_ROOT").$ex);
            }
        }
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath=$dir.DIRECTORY_SEPARATOR.$file;
                if(is_file($fullpath) && !in_array($fullpath,$exclude_arr)) {
                    @unlink($fullpath);
                }
            }
        }
        closedir($dh);
    }


    public function user_verified($uid)
    {
        //校验成功标记用户为已经验证用户
        $this->user_model->update($uid,array('verify' => 1));
    }

    /**
     * 取得用户头像
     * @param $face
     * @return string
     */
    public function fetch_avatar($face){
        if(empty($face)){
            return site_url('/static/img/default.gif');
        }else if(strpos($face, 'http://') === 0 || strpos($face, 'https://') === 0){
            return $face;
        }else{
            return site_url($face);
        }
    }

    public function fetch_remote_avatar($url){
        //var_dump(strpos($url, 'http://'));
        if(empty($url) || (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0)){
            return $url;
        }
        $img = $this->curl->simple_get($url);
        $default_path = $this->config->item("default_upload_path");
        $default_url = $this->config->item("default_upload_url");
        $file_name = md5($url).".jpg";
        $save_path = $default_path."user/oauth2.0/";
        Common::create_folder($save_path);
        file_put_contents($save_path.$file_name,$img);
        return $default_url."user/oauth2.0/".$file_name;
    }

}
